﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TimeAlert
{
    public class Business
    {
        public static List<ExamDto> GetExamFullList()
        {
            Storage storage = ReadExamInfo();
            var list = new List<ExamDto>();
            storage.ExamList.ForEach(exam =>
            {
                var stages = storage.StageList.FindAll(x => x.ExamId == exam.Id);
                var s = stages.Select(x => new StageDto
                {
                    Audio = x.Audio,
                    Name = x.Name,
                    StartTime = x.BeginOrEnd == 1 ? exam.StartTime.AddMinutes(x.Minutes) : exam.EndTime.AddMinutes(-x.Minutes)
                }).ToList();
                ExamDto dto = new ExamDto()
                {
                    Id = exam.Id,
                    ExamName = exam.ExamName,
                    StartTime = exam.StartTime,
                    EndTime = exam.EndTime,
                    StageList = s
                };
                list.Add(dto);
            });

            return list;
        }

        public static Storage ReadExamInfo()
        {
            string examStr = File.ReadAllText(Application.StartupPath + "/Exams.json");
            var exams = JsonConvert.DeserializeObject<List<Exam>>(examStr);

            string stageStr = File.ReadAllText(Application.StartupPath + "/Stages.json");
            var stages = JsonConvert.DeserializeObject<List<Stage>>(stageStr);

            return new Storage() { ExamList = exams, StageList = stages };
        }

        public static void WriteStageInfo(List<Stage> o)
        {
            string s = JsonConvert.SerializeObject(o);
            File.WriteAllText(Application.StartupPath + "/Stages.json", s);
        }
        public static void WriteExamInfo(List<Exam> o)
        {
            string s = JsonConvert.SerializeObject(o);
            File.WriteAllText(Application.StartupPath + "/Exams.json", s);
        }
    }
}
